from selenium import webdriver
import time
import random
from PIL import Image
from util.ShowapiRequest import ShowapiRequest


driver = webdriver.Chrome()

def open_browser():
    driver.get('http://www.5itest.cn/register')
    driver.maximize_window()
    time.sleep(3)


def get_element_id(id):
    '''
    通过元素id获取页面元素
    :param id:
    :return:
    '''
    element = driver.find_element_by_id(id)
    return element


def get_random_user():
    '''
    自动生成用户名，5位
    :return:
    '''
    username = ''.join(random.sample('1234567890abcd',5))
    return username


def get_code_image(filename):
    '''
    获取验证码图片
    :return:
    '''
    driver.save_screenshot(filename)
    code_element = driver.find_element_by_id('getcode_num')
    left = code_element.location['x']
    top = code_element.location['y']
    right = code_element.size['width'] + left
    height = code_element.size['height'] + top
    # 获取窗口可视范围的width和height
    html = driver.find_element_by_tag_name("html")

    # 设置图片重新打开的width和height
    resize_width = html.size['width']
    resize_height = html.size['height']

    # resize图片
    im = Image.open(filename)
    resize_img = im.resize((resize_width, resize_height), Image.BILINEAR)
    # 截取图片
    img = resize_img.crop((left, top, right, height))
    img.save(filename)


def code_online(filename):
    '''
    解析验证码图片图片
    :return:
    '''
    r = ShowapiRequest("http://route.showapi.com/184-4","62626","d61950be50dc4dbd9969f741b8e730f5" )
    r.addBodyPara("typeId", "35")
    r.addBodyPara("convert_to_jpg", "0")
    r.addBodyPara("needMorePrecise", "0")
    r.addFilePara("image", filename)
    res = r.post()
    text = res.json()['showapi_res_body']['Result']
    return text

def main():
    filename = 'E:/study/autostudy/image/test01.png'
    username = get_random_user()
    user_email = username + '@163.com'
    open_browser()
    get_element_id('register_email').send_keys(user_email)
    get_element_id('register_nickname').send_keys(username)
    get_element_id('register_password').send_keys('123456')
    get_code_image(filename)
    text = code_online(filename)
    get_element_id('captcha_code').send_keys(text)
    time.sleep(3)
    get_element_id('register-btn').click()
    driver.close()

if __name__ == '__main__':
   main()
